﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DAL.DBInteractions
{
  public   class EntityRepositoryBase<T> where T: class
    {

        private AuteurContext _dataContext;
        private readonly IDbSet<T> dbset;



        public EntityRepositoryBase(IDBFactory databaseFactory)
        {
            this.DatabaseFactory = databaseFactory;
            this.dbset = DataContext.Set<T>();

        }

        public IDBFactory DatabaseFactory { get; private set; }
        public AuteurContext  DataContext {

            get 
            {
                return _dataContext ?? (_dataContext = DatabaseFactory.Get());
            }
            
            }

        public virtual void Add(T entity)
        {
            dbset.Add(entity);

        }
        public virtual void Update(T entity)
        {
            _dataContext.Entry(entity).State = EntityState.Modified;
        }
        public virtual void Delete(T entity)
        {
            dbset.Remove(entity);

        }

        public virtual void Delete(Func<T, Boolean> predicate)
        {
            IEnumerable<T> objs = dbset.Where<T>(predicate).AsEnumerable();
            foreach (T t in objs)
                dbset.Remove(t);
        }

        public virtual T GetById(int id)
        {
            return dbset.Find(id);

        }

        public virtual T Get(Func<T, Boolean> where)
        {
            return dbset.Where(where).FirstOrDefault<T>();

        }
        public virtual IEnumerable<T> GetAll()
        {
            return dbset.ToList();
        }

        public virtual IEnumerable<T> GetMany(Func<T, bool> where)
        {
            return dbset.Where(where).ToList();

        }
         public virtual IQueryable<T> Find(Func<T, bool> where)
        {
            return dbset.Where(where).AsQueryable();

        }

         public virtual IQueryable<T> FindAuthor(Func<T, bool> where)
         {
             return dbset.Where(where).AsQueryable();
         }




     


        public virtual void save()
        {
            _dataContext.SaveChanges();

        }

        protected virtual void Dispose(bool disposing)
        {
            if (_dataContext != null)
            {
                _dataContext.Dispose();
            }


        }





    }
}
